package com.ibeeking.gmc.global.g.rest.service.impl;

import com.ibeeking.gmc.global.g.rest.service.ITenantEnterpriseInfoService;
import com.ibeeking.found.common.config.prop.FileOssProp;
import com.ibeeking.found.common.utils.DataUtils;
import com.ibeeking.found.common.utils.DateUtils;
import com.ibeeking.found.common.utils.UrlUtils;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.gmc.global.service.common.constants.enums.TenantAuditStatusEnum;
import com.ibeeking.gmc.global.service.common.dos.TenantEnterpriseInfoDO;
import com.ibeeking.gmc.global.service.common.param.TenantEnterpriseInfoParam;
import com.ibeeking.gmc.global.service.common.query.TenantEnterpriseInfoPageQuery;
import com.ibeeking.gmc.global.service.common.query.TenantEnterpriseInfoQuery;
import com.ibeeking.gmc.global.service.common.vo.TenantEnterpriseInfoVO;
import com.ibeeking.gmc.global.service.mapper.TenantEnterpriseInfoMapper;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName TenantEnterpriseInfoServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2020-12-24 13:45
 **/
@Service
public class TenantEnterpriseInfoServiceImpl extends ServiceImpl<TenantEnterpriseInfoMapper, TenantEnterpriseInfoDO> implements ITenantEnterpriseInfoService {

    private static final int ADOPT = 9;//通过
    private static final int REJECT = 2;//驳回
    private static final int UNAUDIT = 1;//未审核

    @Resource
    private TenantEnterpriseInfoMapper tenantEnterpriseInfoMapper;

    @Resource
    private FileOssProp fileOssProp;

    @Override
    public List<TenantEnterpriseInfoVO> list(TenantEnterpriseInfoQuery query) {
        List<TenantEnterpriseInfoDO> tenantEnterpriseInfoDOS = tenantEnterpriseInfoMapper.selectList(new LambdaQueryWrapper<TenantEnterpriseInfoDO>());
        if(Collections3.isEmpty(tenantEnterpriseInfoDOS)) return new ArrayList<>();
        List<TenantEnterpriseInfoVO> TenantEnterpriseInfoResultVO = new ArrayList<>();

        TenantEnterpriseInfoResultVO = tenantEnterpriseInfoDOS.stream().map(d->{
            TenantEnterpriseInfoVO tenantEnterpriseInfoVO = BeanUtil.convertBean(d, TenantEnterpriseInfoVO.class);
            if(d.getBusinessStart() != null){
                tenantEnterpriseInfoVO.setBusinessStart(DateUtils.parseStr(d.getBusinessStart()));
            }
            if(d.getBusinessEnd() != null){
                tenantEnterpriseInfoVO.setBusinessEnd(DateUtils.parseStr(d.getBusinessEnd()));
            }
            //真实经营材料处理 字符串转list
            String realBusinessMaterials = d.getRealBusinessMaterials();
            List<String> realBusinessMaterialsListNew = new ArrayList<>();
            if (StringUtils.isNotBlank(realBusinessMaterials)) {
                List<String> realBusinessMaterialsList = Arrays.asList(realBusinessMaterials.split(","));
                if (Collections3.isNotEmpty(realBusinessMaterialsList)) {
                    for (String realBusinessMaterial : realBusinessMaterialsList) {
                        realBusinessMaterialsListNew.add(UrlUtils.addUrlDomainName(this.fileOssProp.getHost(), realBusinessMaterial));
                    }
                }
            }
            tenantEnterpriseInfoVO.setRealBusinessMaterialsList(realBusinessMaterialsListNew);
            tenantEnterpriseInfoVO.setCertificate(UrlUtils.addUrlDomainName(this.fileOssProp.getHost(), d.getCertificate()));

            return tenantEnterpriseInfoVO;
        }).collect(Collectors.toList());

        return TenantEnterpriseInfoResultVO;
    }

    @Override
    public Page<TenantEnterpriseInfoVO> pageList(TenantEnterpriseInfoPageQuery pageQuery) {
        Page<TenantEnterpriseInfoDO> pages = tenantEnterpriseInfoMapper.selectPage(new Page<TenantEnterpriseInfoDO>(), new LambdaQueryWrapper<TenantEnterpriseInfoDO>());

        Page<TenantEnterpriseInfoVO> resultPageVOS = BeanUtil.convertPage(pages, TenantEnterpriseInfoVO.class);

        return resultPageVOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(TenantEnterpriseInfoParam param) {
        TenantEnterpriseInfoDO tenantEnterpriseInfoDO = BeanUtil.convertBean(param, TenantEnterpriseInfoDO.class);

        if (StringUtils.isNotBlank(param.getBusinessStart())) {
            tenantEnterpriseInfoDO.setBusinessStart(DateUtils.strToLocalDate(param.getBusinessStart()));
        }

        if(param.getBusinessTermType() == 2){
            tenantEnterpriseInfoDO.setBusinessEnd(null);
        }else {
            if(StringUtils.isNotBlank(param.getBusinessEnd())){
                tenantEnterpriseInfoDO.setBusinessEnd(DateUtils.strToLocalDate(param.getBusinessEnd()));
            }
        }
        List<String> realBusinessMaterials = param.getRealBusinessMaterialsList();
        List<String> realBusinessMaterialsListNew = new ArrayList<>();
        if (Collections3.isNotEmpty(realBusinessMaterials)) {
            for (String realBusinessMaterial : realBusinessMaterials) {
                realBusinessMaterialsListNew.add(UrlUtils.removeMallUrlDomainName(fileOssProp.getHost(), realBusinessMaterial));
            }
        }
        tenantEnterpriseInfoDO.setCertificate(UrlUtils.removeMallUrlDomainName(fileOssProp.getHost(), tenantEnterpriseInfoDO.getCertificate()));

        tenantEnterpriseInfoDO.setCreateTime(LocalDateTime.now());
        tenantEnterpriseInfoDO.setModifyTime(LocalDateTime.now());
        return tenantEnterpriseInfoMapper.insert(tenantEnterpriseInfoDO) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modify(TenantEnterpriseInfoParam param) {
        TenantEnterpriseInfoDO tenantEnterpriseInfoDO = BeanUtil.convertBean(param, TenantEnterpriseInfoDO.class);
        if (tenantEnterpriseInfoDO.getCertificate().indexOf(fileOssProp.getHost()) >= 0) {
            tenantEnterpriseInfoDO.setCertificate(tenantEnterpriseInfoDO.getCertificate().substring(fileOssProp.getHost().length()));
        }
        if(StringUtils.isNotBlank(param.getBusinessStart())){
            tenantEnterpriseInfoDO.setBusinessStart(DateUtils.strToLocalDate(param.getBusinessStart()));
        }
        if(param.getBusinessTermType() == 2){
            tenantEnterpriseInfoDO.setBusinessEnd(null);
        }else {
            if(StringUtils.isNotBlank(param.getBusinessEnd())){
                tenantEnterpriseInfoDO.setBusinessEnd(DateUtils.strToLocalDate(param.getBusinessEnd()));
            }
        }
        List<String> realBusinessMaterials = param.getRealBusinessMaterialsList();
        List<String> realBusinessMaterialsListNew = new ArrayList<>();
        if (Collections3.isNotEmpty(realBusinessMaterials)) {
            for (String realBusinessMaterial : realBusinessMaterials) {
                realBusinessMaterialsListNew.add(UrlUtils.removeMallUrlDomainName(fileOssProp.getHost(), realBusinessMaterial));
            }
        }
        tenantEnterpriseInfoDO.setCertificate(UrlUtils.removeMallUrlDomainName(fileOssProp.getHost(), tenantEnterpriseInfoDO.getCertificate()));

        tenantEnterpriseInfoDO.setModifyTime(LocalDateTime.now());
        return tenantEnterpriseInfoMapper.updateById(tenantEnterpriseInfoDO) > 0;
    }

    @Override
    public TenantEnterpriseInfoVO view(Long id) {
        TenantEnterpriseInfoDO tenantEnterpriseInfoDO = tenantEnterpriseInfoMapper.selectById(id);
        TenantEnterpriseInfoVO tenantEnterpriseInfoVO = BeanUtil.convertBean(tenantEnterpriseInfoDO, TenantEnterpriseInfoVO.class);
        if(tenantEnterpriseInfoDO.getBusinessStart() != null){
            tenantEnterpriseInfoVO.setBusinessStart(DateUtils.parseStr(tenantEnterpriseInfoDO.getBusinessStart()));
        }
        if(tenantEnterpriseInfoDO.getBusinessEnd() != null){
            tenantEnterpriseInfoVO.setBusinessEnd(DateUtils.parseStr(tenantEnterpriseInfoDO.getBusinessEnd()));
        }
        //真实经营材料处理 字符串转list
        String realBusinessMaterials = tenantEnterpriseInfoDO.getRealBusinessMaterials();
        List<String> realBusinessMaterialsListNew = new ArrayList<>();
        if (StringUtils.isNotBlank(realBusinessMaterials)) {
            List<String> realBusinessMaterialsList = Arrays.asList(realBusinessMaterials.split(","));
            if (Collections3.isNotEmpty(realBusinessMaterialsList)) {
                for (String realBusinessMaterial : realBusinessMaterialsList) {
                    realBusinessMaterialsListNew.add(UrlUtils.addUrlDomainName(this.fileOssProp.getHost(), realBusinessMaterial));
                }
            }
        }
        tenantEnterpriseInfoVO.setRealBusinessMaterialsList(realBusinessMaterialsListNew);
        tenantEnterpriseInfoVO.setCertificate(UrlUtils.addUrlDomainName(this.fileOssProp.getHost(), tenantEnterpriseInfoVO.getCertificate()));
        return tenantEnterpriseInfoVO;
    }

    @Override
    public Boolean exist(Long id){
        TenantEnterpriseInfoDO tenantEnterpriseInfoDO = tenantEnterpriseInfoMapper.selectById(id);
        return tenantEnterpriseInfoDO != null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean del(Long id) {
        return tenantEnterpriseInfoMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delByTenantId(Integer tenantId) {
        TenantEnterpriseInfoVO vo = this.viewByTenantId(tenantId);
        if (vo == null) {
            throw new BusinessException("请求资源失败");
        }
        return this.del(vo.getId());
    }

    @Override
    public TenantEnterpriseInfoVO viewByTenantId(Integer tenantId) {
        QueryWrapper<TenantEnterpriseInfoDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TenantEnterpriseInfoDO::getTenantId, tenantId);
        TenantEnterpriseInfoDO tenantEnterpriseInfoDO = this.tenantEnterpriseInfoMapper.selectOne(queryWrapper);
        if (tenantEnterpriseInfoDO == null) {
            return null;
        }
        TenantEnterpriseInfoVO vo = BeanUtil.convertBean(tenantEnterpriseInfoDO, TenantEnterpriseInfoVO.class);
        if(tenantEnterpriseInfoDO.getBusinessStart() != null){
            vo.setBusinessStart(DateUtils.parseStr(tenantEnterpriseInfoDO.getBusinessStart()));
        }
        if(tenantEnterpriseInfoDO.getBusinessEnd() != null){
            vo.setBusinessEnd(DateUtils.parseStr(tenantEnterpriseInfoDO.getBusinessEnd()));
        }
        //真实经营材料处理 字符串转list
        String realBusinessMaterials = tenantEnterpriseInfoDO.getRealBusinessMaterials();
        List<String> realBusinessMaterialsListNew = new ArrayList<>();
        if (StringUtils.isNotBlank(realBusinessMaterials)) {
            List<String> realBusinessMaterialsList = Arrays.asList(realBusinessMaterials.split(","));
            if (Collections3.isNotEmpty(realBusinessMaterialsList)) {
                for (String realBusinessMaterial : realBusinessMaterialsList) {
                    realBusinessMaterialsListNew.add(UrlUtils.addUrlDomainName(this.fileOssProp.getHost(), realBusinessMaterial));
                }
            }
        }
        vo.setRealBusinessMaterialsList(realBusinessMaterialsListNew);
        vo.setCertificate(UrlUtils.addUrlDomainName(this.fileOssProp.getHost(), vo.getCertificate()));
        return vo;
    }

    @Override
    public Boolean save(TenantEnterpriseInfoParam param) {
        Integer auditStatus = param.getAuditStatus();
        if (auditStatus == null) {
            auditStatus = TenantAuditStatusEnum.SUBMIT_NO.getValue();
            param.setAuditStatus(auditStatus);
        }
        DataUtils.trueThrowException(TenantAuditStatusEnum.AUDIT_NO.getValue().equals(auditStatus), "当前信息待审核,禁止修改");
        DataUtils.trueThrowException(TenantAuditStatusEnum.AUDIT_YES.getValue().equals(auditStatus), "当前信息已审核,禁止修改");
        Integer businessTermType = param.getBusinessTermType();

        List<String> realBusinessMaterials = param.getRealBusinessMaterialsList();
        List<String> realBusinessMaterialsListNew = new ArrayList<>();
        if (Collections3.isNotEmpty(realBusinessMaterials)) {
            for (String realBusinessMaterial : realBusinessMaterials) {
                realBusinessMaterialsListNew.add(UrlUtils.removeMallUrlDomainName(fileOssProp.getHost(), realBusinessMaterial));
            }
        }
        TenantEnterpriseInfoDO tenantEnterpriseInfoDO = BeanUtil.convertBean(param, TenantEnterpriseInfoDO.class);
        if (businessTermType == 2) {
            param.setBusinessEnd(null);
        } else {
            DataUtils.trueThrowException(StringUtils.isBlank(param.getBusinessEnd()), "请填写营业期限结束日期");
            tenantEnterpriseInfoDO.setBusinessEnd(DateUtils.strToLocalDate(param.getBusinessEnd()));
        }
        DataUtils.trueThrowException(StringUtils.isBlank(param.getBusinessStart()), "请填写营业期限结束日期");
        tenantEnterpriseInfoDO.setBusinessStart(DateUtils.strToLocalDate(param.getBusinessStart()));
        Long userId = UserUtils.getUserId();
        TenantEnterpriseInfoVO enterpriseInfoOld = viewByTenantId(param.getTenantId());
        if (enterpriseInfoOld != null) {
            tenantEnterpriseInfoDO.setId(enterpriseInfoOld.getId());
            tenantEnterpriseInfoDO.setModifyBy(userId);
            tenantEnterpriseInfoDO.setAuditStatus(enterpriseInfoOld.getAuditStatus());
        } else {
            tenantEnterpriseInfoDO.setAuditStatus(TenantAuditStatusEnum.SUBMIT_NO.getValue());
            tenantEnterpriseInfoDO.setCreateBy(userId);
        }
        tenantEnterpriseInfoDO.setCertificate(UrlUtils.removeMallUrlDomainName(fileOssProp.getHost(), tenantEnterpriseInfoDO.getCertificate()));
        tenantEnterpriseInfoDO.setRealBusinessMaterials(Collections3.join(realBusinessMaterialsListNew, ","));
        tenantEnterpriseInfoDO.setCreateTime(LocalDateTime.now());
        tenantEnterpriseInfoDO.setModifyTime(LocalDateTime.now());
        return saveOrUpdate(tenantEnterpriseInfoDO);
    }

    @Override
    public Boolean changeStatus(Integer tenantId, Integer auditStatus) {
        DataUtils.trueThrowException(tenantId == null || auditStatus == null, "审核状态修改失败!");
        return getBean().update(Wrappers.lambdaUpdate(TenantEnterpriseInfoDO.class).eq(TenantEnterpriseInfoDO::getTenantId, tenantId).set(TenantEnterpriseInfoDO::getAuditStatus, auditStatus));
    }

    private static TenantEnterpriseInfoServiceImpl getBean() {
        return SpringBeanUtil.getBean(TenantEnterpriseInfoServiceImpl.class);
    }
}
